<template>
	<div class="app-mob-picker">
		<van-field
			v-bind="$attrs"
			class="app-mob-picker__input"
			v-model="curValue"
			:disabled="disabled"
			readonly
			:placeholder="placeholder"
			@click="openView"
		>
			<template #right-icon>
				<van-icon v-if="!curValue" name="search" />
				<van-icon v-else name="clear" @click="clear" />
			</template>
		</van-field>
	</div>
</template>
<script lang="ts" setup>
import { deepCopy, IEvent, IParam, isExistAndNotEmpty } from '@/core';
import { handleEditorNavParams, useEditorTypeParams } from '@/hooks/use-editor';
import { Ref } from 'vue';
import { dataPickerProps } from './data-picker';
interface EditorEmit {
	(name: 'editor-event', value: IEvent<string>): void;
}
const props = defineProps(dataPickerProps);
// 类型校验
const {
	validateConfig,
	valueType,
	valueSeparator,
	objectNameField,
	objectIdField,
	objectValueField,
} = useEditorTypeParams();
validateConfig();
const emit = defineEmits<EditorEmit>();
const items: Ref<any[]> = ref([]);

const { navContext, navViewParam } = handleEditorNavParams(props);

let curValue: Ref<any> = computed(() => {
	let value: any;
	let item: any = deepCopy(props.value as any);
	try {
		if (item) {
			if (props.multiple) {
				value = [];
				const _items: any[] = valueType == 'OBJECTS' ? item : JSON.parse(item);
				const textFiled: string =
					valueType == 'OBJECTS'
						? objectNameField || props.deMajorField
						: props.deMajorField;
				_items.forEach((_item: any) => {
					value.push(_item[textFiled]);
				});
				return value.join(valueSeparator);
			} else {
				if (valueType == 'OBJECT') {
					value = item[props.deMajorField];
				} else {
					value = item;
				}
			}
		}
	} catch (error) {
		console.log(error);
	}
	return value;
});

// 打开一般视图
const openView = async (event: any) => {
	event.preventDefault();
	event.stopPropagation();
	if (props.disabled) {
		return;
	}
	if (!props.pickupView) {
		return;
	}
	const view = App.getAppViewConfig()?.[props.pickupView];
	if (!view) {
		return;
	}
	const tempViewParams = deepCopy(navViewParam);
	//多选
	if (props.multiple) {
		let selectedData: IParam[] = [];
		try {
			selectedData = props.value
				? valueType == 'OBJECTS'
					? props.value
					: JSON.parse(props.value as string)
				: [];
		} catch (error) {
			selectedData = [];
		}
		Object.assign(tempViewParams, { selectedData: selectedData });
	} else {
		const selectedData: IParam = {};
		if (
			props.data &&
			props.valueItem &&
			isExistAndNotEmpty(props.data[props.valueItem])
		) {
			Object.assign(selectedData, { srfkey: props.data[props.valueItem] });
		}
		if (isExistAndNotEmpty(`${props.value}`)) {
			Object.assign(selectedData, { srfmajortext: props.value });
		}
		Object.assign(tempViewParams, { selectedData: [selectedData] });
	}

	let openMode: 'openPage' | 'openModal' = 'openPage';
	// 选择视图不支持路由打开 默认为模态
	if (Object.is(view.openMode, 'INDEXVIEWTAB')) {
		openMode = 'openModal';
	}
	//打开视图
	const result = await App.getOpenViewHelper()[openMode](
		view,
		deepCopy(navContext),
		tempViewParams
	);
	if (result && result.ok && result.data && result.data.length > 0) {
		doEditorEmit(result.data);
	}
};

const clear = (event: any) => {
	event.stopPropagation();
	event.preventDefault();
	if (props.multiple) {
		emit('editor-event', {
			name: `${props.name}`,
			action: 'valueChange',
			data: JSON.stringify([]),
		});
	} else {
		if (props.valueItem) {
			emit('editor-event', {
				name: props.valueItem,
				action: 'valueChange',
				data: null,
			});
		}
		emit('editor-event', {
			name: `${props.name}`,
			action: 'valueChange',
			data: '',
		});
	}
};

// 处理对象类型参数
const handleObjectParams = (item: IParam, otherParams: IParam): IParam => {
	const object: IParam = { ...otherParams };
	if (objectNameField) {
		Object.assign(object, {
			[objectNameField]: item[objectNameField],
		});
	}
	if (objectIdField) {
		Object.assign(object, {
			[objectIdField]: item[objectIdField],
		});
	}
	if (objectValueField) {
		Object.assign(object, {
			[objectValueField]: deepCopy(item),
		});
	}
	return object;
};

// 编辑器抛值
const doEditorEmit = (data: any[]): any => {
	if (props.multiple) {
		let value: any = null;
		//返回一个JSON数组字符串
		let selects: any[] = [];
		data.forEach((item: any, i: number) => {
			const index = items.value.findIndex((_item: any) =>
				Object.is(item[props.deKeyField], _item[props.deKeyField])
			);
			if (index < 0) {
				items.value.push(item);
			}
			let selected: IParam = {
				srfmajortext: item[props.deMajorField],
				srfkey: item[props.deKeyField],
			};
			if (valueType == 'OBJECTS') {
				selected = handleObjectParams(item, selected);
			}
			selects.push(selected);
		});
		value =
			selects.length > 0
				? valueType == 'OBJECTS'
					? selects
					: JSON.stringify(selects)
				: null;
		emit('editor-event', {
			name: `${props.name}`,
			action: 'valueChange',
			data: value,
		});
	} else {
		if(data?.length ===0) {
			return;
		}
		//返回一个字符串
		let value: any ;
		let keyValue: any = '';
		if (valueType == 'OBJECT') {
			value = handleObjectParams(data[0], { [props.deMajorField]: data[0][props.deMajorField] });
		}else{
			value = '';
			value = value + data[0][props.deMajorField];
		}
		keyValue = keyValue + data[0][props.deKeyField];
		if (props.valueItem) {
			emit('editor-event', {
				name: props.valueItem,
				action: 'valueChange',
				data: keyValue,
			});
		}
		emit('editor-event', {
			name: `${props.name}`,
			action: 'valueChange',
			data: value,
		});
		return;
	}
};
</script>
